<?php

/**
 * 图片空间
 *
 * @author birdy <freebirdy@foxmail.com>
 * @link http://www.aiyuangong.com
 */

namespace app\seller\controller;

class Album extends \app\common\controller\Seller
{

    /**
     * 相册
     */
    public function index()
    {
        $sort = input('sort/d', 4);
        $param = [];
        $param['order'] = 'aclass_sort desc,aclass_id asc';
        switch ($sort) {
            case '0':
                $param['order'] = 'upload_time desc';
                break;
            case '1':
                $param['order'] = 'upload_time asc';
                break;
            case '2':
                $param['order'] = 'aclass_name desc';
                break;
            case '3':
                $param['order'] = 'aclass_name asc';
                break;
            case '4':
                $param['order'] = 'aclass_sort desc,aclass_id asc';
                break;
            case '5':
                $param['order'] = 'aclass_sort asc';
                break;
        }
        $this->assign('sort', $sort);
        $this->assign('lists', $this->getAlbumList($param));
        $this->assign('left_nav', 'album');
        return view();
    }

    /**
     * 添加/编辑 相册
     */
    public function modify()
    {
        if ($this->request->isPost()) {
            $param = array();
            $sort = input('post.sort/d', 0);
            $param['aclass_name'] = input('post.name', '', 'htmlspecialchars');
            $param['aclass_des'] = mb_substr(input('post.description', '', 'htmlspecialchars'), 0, 100);
            $param['aclass_sort'] = ($sort < 0 || $sort > 255) ? 255 : $sort;
            $id = input('post.id/d', 0);
            if ($id > 0) {
                $param['upload_time'] = time();
                $map = [
                    'store_id' => $this->store_id,
                    'aclass_id' => $id
                ];
                $rs = rpc("common/common/update", ['album_class', $map, $param]);
                $tip = '编辑';
            } else {
                $param['store_id'] = $this->store_id;
                $param['upload_time'] = time();
                $rs = rpc("common/common/create", ['album_class', $param]);
                $tip = '创建';
            }

            if ($rs) {
                showDialog('相册' . $tip . '成功', 'reload', 'succ', $this->request->isAjax() ? 'CUR_DIALOG.close();' : '');
            } else {
                showDialog('相册' . $tip . '失败：' . \think\Db::getLastSql());
            }
        }

        $id = input('id/d', 0);
        if ($id > 0) {
            $map = [
                'store_id' => $this->store_id,
                'aclass_id' => $id
            ];
            $item = rpc('common/common/one', ['album_class', $map]);
            $this->assign('item', $item);
        }
        $this->assign('left_nav', 'album');
        return view();
    }

    public function album_del()
    {
        //to do 删除相册
    }

    /**
     * 图片删除
     */
    public function pic_del()
    {
        $id = input('get.id', 0, 'intval');
        $id < 1 && $id = implode(",", input('post.id/a'));
        !$id && showDialog('图片删除失败');

        $map = [
            'store_id' => $this->store_id,
            'apic_id' => ['in', $id]
        ];
        $pics = rpc("common/common/lists", ['album_pic', $map]);
        !$pics && showDialog('图片删除成功', 'reload', 'succ');

        if (rpc("common/common/delete", ['album_pic', $map])) {
            foreach ($pics as $pics) {
                $file = ROOT_PATH . 'public/uploads/' . $pics['apic_cover'];
                $thumb = config('image_thumb');
                $del_files = [$file];
                foreach ($thumb as $thumb) {
                    $path = dirname($file);
                    $del_files[] = $path . "/" . $thumb[0] . "x" . $thumb[1] . '_' . basename($file);
                }

                //删除原图和缩略图
                foreach ($del_files as $del_files) {
                    is_file($del_files) && @unlink($del_files);
                }
            }
            showDialog('图片删除成功', 'reload', 'succ');
        }

        showDialog('图片删除失败');
    }

    /**
     * 图片列表
     */
    public function pic_list()
    {
        $data = $this->getAlbumList();
        $this->view->assign('lists', $data);
        $id = input('id/d');
        if ($id < 1) {
            $album = $data[0];
            $id = $album['aclass_id'];
        } else {
            $data = reset_by_key($data, 'aclass_id');
            if (!isset($data[$id])) {
                $this->error('相册不存在');
            }
            $album = $data[$id];
        }

        $sort = input('sort/d');
        $param = [];
        $param['order'] = 'upload_time desc';
        switch ($sort) {
            case '0':
                $param['order'] = 'upload_time desc';
                break;
            case '1':
                $param['order'] = 'upload_time asc';
                break;
            case '2':
                $param['order'] = 'apic_size desc';
                break;
            case '3':
                $param['order'] = 'apic_size asc';
                break;
            case '4':
                $param['order'] = 'apic_name desc';
                break;
            case '5':
                $param['order'] = 'apic_name asc';
                break;
        }
        $this->assign('sort', $sort);
        $pics = $this->getAlbumPics($id, $param);
        $this->assign('pics', $pics);
        $this->assign('album', $album);
        
        if ($this->request->isAjax()) {
            $item = input('item', 'des');
            $this->assign('color', input('color/d', 0));
            return view('album/pic_list_ajax_'.$item);
        } else {
            $this->assign('left_nav', 'album');
            return view('album/pic_list');
        }
    }

    /**
     * 上传图片到相册
     */
    public function image_upload()
    {
        $store_id = $this->store_id;
        $id = input('post.category_id/d');
        $cate = $this->getAlbumList();
        if ($id < 1) { //不传分类ＩＤ，上传到默认相册
            $id = $cate[0]['aclass_id'];
        }
        $cate = reset_by_key($cate, 'aclass_id');

        $field = input('field', 'file');
        if ($id < 1 || !isset($cate[$id])) {
            $data = [];
            $error = '上传图片失败';
            $data['state'] = 'false';
            $data['message'] = $error;
            $data['origin_file_name'] = '';
            return json($data);
        }

        //上传
        $rs = $this->uploadFile($field, 'album');
        if (!$rs['status']) {
            $data = [];
            $data['state'] = 'false';
            $data['message'] = $rs['error'] ?: '上传失败';
            $data['origin_file_name'] = '';
            return json($data);
        }

        //获取图片信息
        list($width, $height) = getimagesize($rs['physical_path'] . $rs['save_name']);

        $pic = $rs['save_path_type'] . $rs['save_name'];
        $insert_array = [];
        $insert_array['apic_name'] = $rs['original'];
        $insert_array['apic_tag'] = '';
        $insert_array['aclass_id'] = $id;
        $insert_array['apic_cover'] = $pic;
        $insert_array['apic_size'] = $rs['size'];
        $insert_array['apic_spec'] = $width . 'x' . $height;
        $insert_array['upload_time'] = time();
        $insert_array['store_id'] = $store_id;

        $result = rpc('common/common/create', ['album_pic', $insert_array]);
        
        $data = [];
        $data['file_id'] = $result;
        $data['file_name'] = $pic;
        $data['origin_file_name'] = $rs['original'];
        $data['file_path'] = $pic;

        $thumb = input('thumb/d');
        $thumbConfig = config('image_thumb');
        if (isset($thumbConfig)) {
            $data['thumb'] = img_url($pic, $thumb);
        }
        
        $data['instance'] = input('instance');
        $data['state'] = 'true';

        return json($data);
    }

    /**
     * 替换图片
     * @return json
     */
    public function replace_image_upload()
    {
        $field = input('get.id', '');
        $id = explode("_", $field);
        $id = end($id);
        $map = [
            'store_id' => $this->store_id,
            'apic_id' => $id
        ];
        $pics = rpc("common/common/one", ['album_pic', $map]);
        if ($id < 1 || !$pics) {
            return json(['state' => 'false', 'message' => '图片替换失败']);
        }

        $replace = 'uploads/' . $pics['apic_cover'];
        $rs = $this->uploadFile($field, 'replace', false, ['original' => $replace]);
        if (!$rs['status']) {
            return json(['state' => 'false', 'message' => $rs['error']]);
        }

        list($width, $height) = getimagesize(ROOT_PATH . 'public/' . $replace);

        $param = array();
        $param['apic_size'] = $rs['size'];
        $param['apic_spec'] = $width . 'x' . $height;
        rpc('common/common/update', ['album_pic', $map, $param]);

        //删除旧图缩略图
        $file = ROOT_PATH . 'public/' . $replace;
        $thumb = config('image_thumb');
        $del_files = [];
        foreach ($thumb as $thumb) {
            $path = dirname($file);
            $del_files[] = $path . "/" . $thumb[0] . "x" . $thumb[1] . '_' . basename($file);
        }

        //删除原图和缩略图
        foreach ($del_files as $del_files) {
            is_file($del_files) && @unlink($del_files);
        }

        return json(['state' => 'true', 'id' => $id]);
    }

    /**
     * 修改相册封面
     */
    public function change_album_cover()
    {
        $id = input('get.id/d', 0);
        $map = [
            'store_id' => $this->store_id,
            'apic_id' => $id
        ];
        $pics = rpc("common/common/one", ['album_pic', $map]);
        if ($id < 1 || !$pics) {
            showDialog('相册封面设置失败');
        }

        $update = ['aclass_cover' => $pics['apic_cover']];
        $map = [
            'store_id' => $this->store_id,
            'aclass_id' => $pics['aclass_id']
        ];

        rpc("common/common/update", ['album_class', $map, $update]);
        showDialog('相册封面设置成功', 'reload', 'succ');
    }

    /**
     * 图片转移
     */
    public function pic_move()
    {
        // to do 移动
    }

    /**
     * 修改图片名称
     * @return string
     */
    public function change_pic_name()
    {
        $id = input('post.id/d', 0);
        $name = mb_substr(input('post.name', '', 'htmlspecialchars'), 0, 50);

        if (empty($id) && empty($name)) {
            return 'false';
        }

        $map = [
            'store_id' => $this->store_id,
            'apic_id' => $id
        ];
        $update = ['apic_name' => $name];
        $rs = rpc("common/common/update", ['album_pic', $map, $update]);

        return 'true';
    }

    /**
     * 获取单个相册图片
     * @param type $album_id
     */
    protected function getAlbumPics($album_id, $other = [])
    {
        $map = [
            'store_id' => $this->store_id,
            'aclass_id' => $album_id
        ];

        return $this->db_lists_page('album_pic', $map, 10, $other);
    }

    /**
     * 获取相册列表，如果不存在，默认创建一个
     * @return type
     */
    protected function getAlbumList($other = [])
    {
        $map = [
            'store_id' => $this->store_id
        ];

        if (!$other) {
            //保证默认相册在第一个
            $other['order'] = 'aclass_id asc';
        }

        $rs = rpc("common/common/lists", ['album_class', $map, $other]);
        if (!$rs) {
            $data = [
                'aclass_name' => '默认相册',
                'store_id' => $this->store_id,
                'upload_time' => time(),
                'is_default' => 1
            ];
            $data['aclass_id'] = rpc("common/common/create", ['album_class', $data]);
            $rs = [$data];
        }

        return $rs;
    }

}
